package com.bci.pwtz.servlet;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bci.pwtz.admin.service.AdminDictionaryService;
import com.bci.pwtz.admin.service.AdminMenuService;
import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.model.DeviceType;
import com.bci.pwtz.mysql.model.DictionaryType;
import com.bci.pwtz.service.BatchUpdateService;
import com.bci.pwtz.service.BusinessRefService;
import com.bci.pwtz.service.CompanyMenuService;
import com.bci.pwtz.service.ConfigService;
import com.bci.pwtz.service.DeviceTypeService;
import com.bci.pwtz.service.GeoCodeService;
import com.bci.pwtz.service.SensitiveWordService;
import com.bci.pwtz.task.TaskManager;
import com.bci.pwtz.task.thread.ClearAuditThread;
import com.bci.pwtz.task.thread.ClearInvationCodeThread;
import com.bci.pwtz.task.thread.ClearTokenThread;
import com.bci.pwtz.task.thread.ClearVIPCompanyThread;

/**
 * 容器启动事件监听，用来启动全局或则缓存数据<br/>
 * <p>
 * Description:<br/>
 * <p>
 * 
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 *       <listener>
 *     <listener-class>com.bcinfo.upp.admin.servlet.UppAdminListener</listener-class>
 *   </listener>
 * </PRE>
 * <p>
 */
public class InitListener implements ServletContextListener
{

    private final static Logger _logger = Logger.getLogger(InitListener.class);

    /*
     * (non-Javadoc) Description: <br/>
     * 
     * @param sce
     * 
     * @see
     * javax.servlet.ServletContextListener#contextInitialized(javax.servlet
     * .ServletContextEvent)
     */
    @Override
    public void contextInitialized(ServletContextEvent sce)
    {
        // 把所有action数据初始化到map
        _logger.info("数据初始化");
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sce
                .getServletContext());

        
        ConfigService cs = (ConfigService) webApplicationContext.getBean("configService");
        BusinessRefService businessRefSerivce = (BusinessRefService) webApplicationContext.getBean("businessRefService");
        SensitiveWordService sensitiveWordService = (SensitiveWordService) webApplicationContext.getBean("sensitiveWordService");
        CompanyMenuService companyMenuService = (CompanyMenuService) webApplicationContext.getBean("companyMenuService");
        AdminMenuService adminMenuService = (AdminMenuService) webApplicationContext.getBean("adminMenuService");
        GeoCodeService geoCodeService = (GeoCodeService) webApplicationContext.getBean("geoCodeService");
        DeviceTypeService deviceTypeService = (DeviceTypeService) webApplicationContext.getBean("deviceTypeService");
        BatchUpdateService batchUpdateService = (BatchUpdateService) webApplicationContext.getBean("batchUpdateService");
        AdminDictionaryService adminDictionaryService = (AdminDictionaryService)webApplicationContext.getBean("adminDictionaryService");
        try
        {
            PwtzConstants.mutiPatternParserMap = sensitiveWordService.initMutiPatternParserMap();
            PwtzConstants.PROVINCE_MAP = geoCodeService.findGeoByLevel("1");
            PwtzConstants.CITY_MAP = geoCodeService.findGeoByLevel("2");
            PwtzConstants.COUNTRY_MAP = geoCodeService.findGeoByLevel("3");
            
            PwtzConstants.INTERFACE_SCRECTKEY = cs.getConfigByKey("InterfaceScrectKey");
            PwtzConstants.PASSWORD_KEY = cs.getConfigByKey("PasswordKey");
            PwtzConstants.INVITATION_CODE_VALID = Integer.parseInt(cs.getConfigByKey("InvitationCodeValid"));
            PwtzConstants.DEFAULT_PAGESIZE = Integer.parseInt(cs.getConfigByKey("DefaultPagesize"));
            PwtzConstants.TOKEN_VAILD = Integer.parseInt(cs.getConfigByKey("TokenVaild"));
            PwtzConstants.BUSINESS_REF_CACHE = businessRefSerivce.getBusinessRefList();
            PwtzConstants.CLEAR_TOKEN_INTERVAL = Integer.parseInt(cs.getConfigByKey("ClearTokenInterval"));
            PwtzConstants.CLEAR_INVITATION_CODE_INTERVAL = Integer.parseInt(cs.getConfigByKey("ClearInvitationCodeInterval"));
            PwtzConstants.AUDIT_BYQ_INTERVAL = Integer.parseInt(cs.getConfigByKey("AuditByqInterval"));
            PwtzConstants.CLEAR_COMPANY_VIP_INTERVAL = Integer.parseInt(cs.getConfigByKey("ClearCompanyVipInterval"));
            PwtzConstants.VERIFY_CODE_VAILD = Integer.parseInt(cs.getConfigByKey("VerifyCodeVaild"));
            
            PwtzConstants.MAX_COUNT_VERIFY_CODE_DAILY = Integer.parseInt(cs.getConfigByKey("MaxCountVerifyCodeDaily"));
            PwtzConstants.LOGIN_COOKIE_VAILD = Integer.parseInt(cs.getConfigByKey("LoginCookieVaild"));
            
            PwtzConstants.UMENG_APP_KEY = cs.getConfigByKey("UMengAppKey");            
            PwtzConstants.UMENG_APP_MASTER_SECRET = cs.getConfigByKey("UMengAppMasterSecret");
            
            PwtzConstants.DEFAULT_ADMIN_ROLE_ACTION_CODES = cs.getConfigsByKey("DefaultAdminRoleActionCodes");
            PwtzConstants.DEFAULT_USER_ROLE_ACTION_CODES = cs.getConfigsByKey("DefaultUserRoleActionCodes");
            

            PwtzConstants.SMS_INTERFACE_SEND_URL = cs.getConfigByKey("SmsInterfaceSendUrl");
            PwtzConstants.SMS_INTERFACE_CORP_ID = cs.getConfigByKey("SmsInterfaceCorpID");
            PwtzConstants.SMS_INTERFACE_PASSWORD = cs.getConfigByKey("SmsInterfacePassword");
            PwtzConstants.SMS_INTERFACE_TIMEOUT = Integer.parseInt(cs.getConfigByKey("SmsInterfaceTimeout"));
            PwtzConstants.THREAD_SLEEP_TIME=Integer.parseInt(cs.getConfigByKey("ThreadSleepTime"));
            
            PwtzConstants.AUDIT_VALID = Integer.parseInt(cs.getConfigByKey("AuditValid"));
            PwtzConstants.CLEAR_AUDIT_INTERVAL = Integer.parseInt(cs.getConfigByKey("ClearAuditInterval"));
            
            PwtzConstants.MAX_CREATE_COMPANY_COUNT = Integer.parseInt(cs.getConfigByKey("MaxCreateCompanyCount"));
            PwtzConstants.MAX_JOIN_COMPANY_COUNT = Integer.parseInt(cs.getConfigByKey("MaxJoinCompanyCount"));
            
            PwtzConstants.COMPANY_MENU = companyMenuService.findMenuByPidOrderByRank(0);
            PwtzConstants.ADMIN_MENU = adminMenuService.findMenuByPidOrderByRank(0);
            
            PwtzConstants.MODIFIED_PASSWORD_MSG = cs.getConfigByKey("ModifiedPasswordMsg");
            PwtzConstants.GET_REGISTER_CODE_MSG = cs.getConfigByKey("GetRegisterCodeMsg");
            PwtzConstants.GET_FORGET_PASSWORD_CODE_MSG = cs.getConfigByKey("GetForgetPasswordCodeMsg");
            PwtzConstants.GET_SWITCH_TEL_CODE_MSG = cs.getConfigByKey("GetSwitchTelCodeMsg");
            PwtzConstants.JOIN_COMPANY_MSG = cs.getConfigByKey("JoinCompanyMsg");
            PwtzConstants.ADD_USER_SEND_PASSWORD_MSG = cs.getConfigByKey("AddUserSendPasswordMsg");
            PwtzConstants.AUDIT_SUCCESS_MSG = cs.getConfigByKey("AuditSuccessMsg");
            
            PwtzConstants.VDYSTAT_TEMPLATE = cs.getConfigByKey("vdystatTemplate");
            PwtzConstants.VZYSTAT_TEMPLATE = cs.getConfigByKey("vzystatTemplate");
            PwtzConstants.THE_TRIAL_USERS_COUNT = Integer.parseInt(cs.getConfigByKey("TheTrialUsersCount"),10);
            PwtzConstants.THE_TRIAL_TOWERS_COUNT = Integer.parseInt(cs.getConfigByKey("TheTrialTowersCount"),10);
            List<DeviceType> deviceTypeList = deviceTypeService.selectAll(2);
            for(DeviceType dt :deviceTypeList)
            {
                if(!PwtzConstants.DEVICE_TYPE_MAP.containsKey(dt.getDeviceTypeId()))
                    PwtzConstants.DEVICE_TYPE_MAP.put(dt.getDeviceTypeId(), dt.getDeviceTypeName());
            }
            PwtzConstants.BATCH_UPDATE = batchUpdateService.queryAll();
            
            List<DictionaryType> dictionaryTypeList =  adminDictionaryService.selectDictionaryType();
            for(DictionaryType bean : dictionaryTypeList){
            	if(!PwtzConstants.DICTIONARY_TYPE.containsKey(bean.getDictionaryTypeId()))
            		PwtzConstants.DICTIONARY_TYPE.put(bean.getDictionaryTypeId(), bean.getTypeName());
            }
            
            PwtzConstants.WEB_REAL_PATH = sce.getServletContext().getRealPath("/");
            PwtzConstants.THE_SERVER_TYPE = Integer.parseInt(cs.getConfigByKey("TheServerType"));
        }
        catch (PwtzDatabaseException e)
        {
            _logger.error("数据初始化异常,",e);
        }
        
        _logger.info("后台任务启动");        
        TaskManager.start(new ClearTokenThread());
        TaskManager.start(new ClearInvationCodeThread());
        TaskManager.start(new ClearAuditThread());
        //TaskManager.start(new AuditDeviceDataThread());
        TaskManager.start(new ClearVIPCompanyThread());
    }

    /*
     * (non-Javadoc) Description: <br/>
     * 
     * @param sce
     * 
     * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.
     * ServletContextEvent)
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce)
    {

    }

}
